import uuid

from django.db import models
from django.urls import reverse

from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFill
# Create your models here.

class MusicList(models.Model):
    id = models.CharField(max_length=128, primary_key=True, verbose_name='Id')
    name = models.CharField(max_length=30, verbose_name='音乐名称')
    user = models.ForeignKey('user.User', db_column='user', on_delete=models.CASCADE, verbose_name='用户')
    like_count = models.IntegerField(default=0, verbose_name='点赞次数')
    is_original = models.SmallIntegerField(default=0, verbose_name='是否原创')
    is_download = models.SmallIntegerField(default=0, verbose_name='是否可下载')
    category = models.ForeignKey('MusicCategory', on_delete=models.DO_NOTHING, db_column='category', verbose_name='音乐类型')
    summary = models.CharField(max_length=200, default='该音乐暂无简介', verbose_name='简介')
    upload_time = models.DateTimeField(auto_now_add=True, verbose_name='上传时间')
    music_src = models.FileField(upload_to='mp3', verbose_name='链接地址')
    music_cover = ProcessedImageField(upload_to='cover',
                               default='cover/default.png',
                               verbose_name='音乐封面',
                               processors=[ResizeToFill(500, 500)],)

    class Meta:
        managed = True
        verbose_name = '音乐列表'
        verbose_name_plural = verbose_name
        db_table = 'music_list'

        permissions = (
            ('download', r'下载音乐'),
        )

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.id:
            self.id = uuid.uuid4()
        if len(self.music_cover.name.split('/')) == 1:
            # 用户上传音乐保存在用户名命名的文件夹下
            self.music_cover.name = self.user.username + '/' + self.name + '.jpg'
        self.music_src.name = self.user.username + '/' + self.name + '.mp3'
        super(MusicList, self).save()

    def update(self):
        super(MusicList, self).save()

    def get_absolute_url(self):
        return reverse('music:music_detail', kwargs={'pk': self.id})


class MusicCategory(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='类型Id')
    name = models.CharField(max_length=20, verbose_name='类型名称')

    class Meta:
        managed = True
        verbose_name = '音乐流派'
        verbose_name_plural = verbose_name
        db_table = 'music_category'

    def __str__(self):
        return self.name
